package cn.xu.bookstore.user.dao;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import cn.itcast.jdbc.TxQueryRunner;
import cn.xu.bookstore.user.domain.User;

public class UserDao {
	private QueryRunner qr = new TxQueryRunner();
	
	
	/*
	 * 按照用户名来查找
	 */
	public User findByUsername(String username){
		String sql = "select * from tb_user where username=?";
		try {
			return qr.query(sql, new BeanHandler<User>(User.class),username);
		} catch (SQLException e) {
			throw new RuntimeException();
		}
	}
	
	/*
	 * 按照email来查找
	 */
	public User findByEmail(String email){
		String sql="select * from tb_user where email=?";
		try {
			return qr.query(sql, new BeanHandler<User>(User.class),email);
		} catch (SQLException e) {
			throw new RuntimeException();
		}
	}
	
	/*
	 * 添加用户
	 */
	public void add(User form){
		String sql = "insert into tb_user values(?,?,?,?,?,?)";
		Object[] params = {form.getUid(),form.getUsername(),form.getPassword(),
				form.getEmail(),form.getCode(),form.getState()};
		try {
			qr.update(sql,params);
		} catch (SQLException e) {
			throw new RuntimeException();
		}
	}
	
	/*
	 * 根据激活码来查询该用户
	 */
	public User findByCode(String code ){
		String sql = "select * from tb_user where code = ? ";
		try {
			return qr.query(sql, new BeanHandler<User>(User.class),code);
		} catch (SQLException e) {
			throw new RuntimeException();
		}
	}
	
	/*
	 * 更细该用户的激活状态
	 */
	public void updateState(String uid,Boolean state){
		String sql = "update set tb_user state = ? where code =?";
		try {
			qr.update(sql,state,uid);
		} catch (SQLException e) {
			throw new RuntimeException();
		} 
	}
	
	
	

}
